<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;
use think\WeChat\Oauth;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register','pay','notifyurl'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 会员中心
     */
    public function index()
    {
       
        $config = wechat_config();
        $find = Db::name('third_party_user')
        ->where(['user_id'=>$this->auth->id,'app_id'=>$config['appid']])
        ->find();
        if(!$find){
           $wechat = new \WeChat\Oauth($config);
            $state = $this->auth->id;
            $scope = 'snsapi_base';
            $redirect_url = url('index/user/oauth',[],'',true);
            // 执行操作
            $bind = $wechat->getOauthRedirect($redirect_url, $state, $scope);
            $this->view->assign('bind', $bind); 
            $this->view->assign('bind_status', 0); 
        }else{
             $this->view->assign('bind_status', 1); 
        }
       
        $this->view->assign('title', __('User center'));
        return $this->view->fetch();
    }

    /**
     * 支付
     * @author M
     * @data             2020-02-14
     * @param  [type] $order_id  [description]
     * @return [type]            [description]
     */
    public function pay(){
        $this->error('通道维护');
        $param    = $this->request->param();
        $validate = new Validate([
            'id'     =>'require|number|gt:0',
        ]);
        $validate->message([
            'id.require'     =>'订单参数有误',
            'id.number'      =>'订单参数有误',
            'id.gt'          =>'订单参数有误',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        $thirdpay_config = config('thirdpay_config');
        $order_id = $param['id'];
        $order = Db::name('user_order')
        ->where(['id'=>$order_id,'order_status'=>4,'order_type'=>2])
        ->find();
        if(!$order){
            $this->error("订单不存在");
        }
        $pay_type = $order['pay_type'] ==1?'923':'922';//922:PDD支付宝支付,923:PDD微信支付
        $params = array(
            'pay_memberid'    =>$thirdpay_config['pay_memberid'],
            'pay_orderid'     =>$order['order_no'],
            'pay_applydate'   =>date('Y-m-d H:i:s'),
            'pay_bankcode'    =>$pay_type,
            'pay_notifyurl'   =>url('index/user/notifyurl',[],'',true),
            'pay_callbackurl' =>url('index/user/returnurl',[],'',true),
            'pay_amount'      => intval($order['sell_price'])
        );
        ksort($params);
        $md5str = "";
        foreach ($params as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $sign = strtoupper(md5($md5str . "key=" . $thirdpay_config['key']));
        $params["pay_md5sign"] = $sign;
        $params['pay_productname'] ='OTC买入';
     
        $this->view->assign('action', $thirdpay_config['payurl']);
        $this->view->assign('hidden', $params);
        return $this->view->fetch();
    }

    /**
     * 支付回调
     * @author M
     * @data             2020-02-14
     * @return [type] [description]
     */
    public function notifyurl(){
        $param = $this->request->param();
        $return_info = json_encode($param);
        //file_put_contents("notify.txt",$return_info);
        $returnArray = array( // 返回字段
            'memberid'       =>  $param['memberid'], // 商户ID
            'orderid'        =>  $param['orderid'], // 订单号
            'amount'         =>  $param['amount'], // 交易金额
            'datetime'       =>  $param['datetime'], // 交易时间
            'transaction_id' =>  $param['transaction_id'], // 支付流水号
            'returncode'     =>  $param['returncode'],
        );
        $thirdpay_config = config('thirdpay_config');
        $md5key = $thirdpay_config['key'];
        ksort($returnArray);
        reset($returnArray);
        $md5str = "";
        foreach ($returnArray as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $sign = strtoupper(md5($md5str . "key=" . $md5key));
        if ($sign == $param['sign']) {
            if ($param['returncode'] == '00') {
                   $order = Db::name('user_order')
                   ->where(['order_no'=>$param['orderid'],'order_type'=>2,'order_status'=>4])
                   ->find();
                   if($order){
                    // 启动事务
                        Db::startTrans();
                        try {
                            $res1 = Db::name('user_order')
                            ->where(['id'=>$order['id']])
                            ->update(['paytime'=>time(),
                                'order_status'=>1,
                                'trade_no'=>$param['transaction_id'],
                                'return_info'=>$return_info]);

                            $user_info = Db::name('user')
                            ->where('id',$order['user_id'])
                            ->lock(true)
                            ->find();
                            $needmu = $order['coin_num'];
                            $res2 = Db::name('user')
                            ->where('id', $order['user_id'])
                            ->setInc('pay_mu', $needmu);
                            
                            if($res1&&$res2){
                                //来源:1=币币交易买入,2=币币交易卖出,3=OTC通道买入,4=OTC通道卖出,5=矿机收益,6=动态奖励,7=购买矿机,8=激活矿机,9=撤销订单,10=空投
                                $user_balance_log['user_id']    = $order['user_id'];
                                $user_balance_log['amount']     = $needmu;
                                $user_balance_log['before']     = $user_info['pay_mu'];
                                $user_balance_log['after']      = $user_info['pay_mu'] + $needmu;
                                $user_balance_log['remark']     = 'OTC交易买入';
                                $user_balance_log['type']       = 1;
                                $user_balance_log['log_type']   = 1;
                                $user_balance_log['source']     = 3;
                                $user_balance_log['createtime'] = time();
                                Db::name('user_balance_log')->insert($user_balance_log);
                                // 提交事务
                                Db::commit();
                                exit("ok");
                            }
                        } catch (\think\Exception\DbException $exception) {
                            // 回滚事务
                            Db::rollback();
                        }

                   }
          }
        }
    }

    public function oauth()
    {
        $code = $this->request->get('code');
        if(!$code){
            $this->error('绑定失败',url('user/index'));
        }
        $config = wechat_config();
        try {
            $wechat = new \WeChat\Oauth($config);
            $result = $wechat->getOauthAccessToken();
            $find = Db::name('third_party_user')
            ->where(['app_id'=>$config['appid'],'openid'=>$result['openid']])
            ->find();

            if($find){
                if($find['user_id'] == $this->auth->id){
                    $this->error('你已经绑定了',url('user/index')); 
                }else{
                    $this->error('已经绑定其他账号了',url('user/index'));
                }
            }else{
                $data['user_id']     = $this->auth->id;
                $data['app_id']      = $config['appid'];
                $data['openid']      = $result['openid'];
                $data['create_time'] =time();
                $res = Db::name('third_party_user')->insert($data);
                if($res){
                    $this->success('绑定成功',url('user/index')); 
                }else{
                   $this->error('绑定失败',url('user/index')); 
                }
                
            }
            
        } catch (Exception $e){

            // 异常处理
            echo  $e->getMessage();
            
        }
    }
    
    /**
     * 注册会员
     */
    public function register()
    {
        $invite_code = $this->request->param('invite_code');
        $version = Db::name('version')->order('id desc')->find();
        // if ($this->auth->id) {
        //     $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        // }
        // if ($this->request->isPost()) {
        //     $username = $this->request->post('username');
        //     $password = $this->request->post('password');
        //     $email = $this->request->post('email');
        //     $mobile = $this->request->post('mobile', '');
        //     $captcha = $this->request->post('captcha');
        //     $token = $this->request->post('__token__');
        //     $rule = [
        //         'username'  => 'require|length:3,30',
        //         'password'  => 'require|length:6,30',
        //         'email'     => 'require|email',
        //         'mobile'    => 'regex:/^1\d{10}$/',
        //         'captcha'   => 'require|captcha',
        //         '__token__' => 'require|token',
        //     ];

        //     $msg = [
        //         'username.require' => 'Username can not be empty',
        //         'username.length'  => 'Username must be 3 to 30 characters',
        //         'password.require' => 'Password can not be empty',
        //         'password.length'  => 'Password must be 6 to 30 characters',
        //         'captcha.require'  => 'Captcha can not be empty',
        //         'captcha.captcha'  => 'Captcha is incorrect',
        //         'email'            => 'Email is incorrect',
        //         'mobile'           => 'Mobile is incorrect',
        //     ];
        //     $data = [
        //         'username'  => $username,
        //         'password'  => $password,
        //         'email'     => $email,
        //         'mobile'    => $mobile,
        //         'captcha'   => $captcha,
        //         '__token__' => $token,
        //     ];
        //     $validate = new Validate($rule, $msg);
        //     $result = $validate->check($data);
        //     if (!$result) {
        //         $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
        //     }
        //     if ($this->auth->register($username, $password, $email, $mobile)) {
        //         $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
        //     } else {
        //         $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
        //     }
        // }
        // //判断来源
        // $referer = $this->request->server('HTTP_REFERER');
        // if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
        //     && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
        //     $url = $referer;
        // }
        $domain = $this->request->domain();
        $host = $domain.'/api/';
        $this->view->assign('host', $host);
        $this->view->assign('invite_code', $invite_code);
        $this->view->assign('version', $version);
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url', '', 'trim');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'require|token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($this->auth->login($account, $password)) {
                $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        //注销本站
        $this->auth->logout();
        $this->success(__('Logout successful'), url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }
}
